export default class Upload{
  constructor(object) {
    this.obj = {
      url: '',
      count: 6,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album','camera'],  // 可以指定来源是相册还是相机，默认二者都有
    }
    if(Object.prototype.toString.call(object) === "[object Object]"){
      Object.assign(this.obj, object);
    }else{
      wx.showToast({
        title: '参数必须为对象',
        icon:"icon",
        duration: 2000
      });
    }
     
 
    return this;
  }
  // 上传图片 返回一个图片的数组集合
  async uploadPic(){
    let chooseImageResult = await this.chooseImage()
    console.log("选择图片",chooseImageResult)
 
    let imgArr = await chooseImageResult.tempFilePaths.map(async (item,index) => {
      wx.showLoading({
        title: `正在上传第${index+1}张`
      });
      let uploadFileResult = await this.uploadFile(item)
 
      console.log("上传图片返回结果",uploadFileResult)
      return uploadFileResult.data;
    })
 
    return new Promise((resolve,reject) => {
      Promise.all(imgArr).then((result)=>{
        wx.hideLoading();
        wx.showToast({
          title: '上传成功',
          icon:"none",
          duration: 2000
        });
        console.log("上传图片结果",result)
        resolve(result)
      })
    }) 
  }
  uploadFile(file){
	  var  token = uni.getStorageSync("openid");
    return new Promise((resolve, reject) => {
		console.log(file);
      wx.uploadFile({
       url: this.obj.url,
       filePath: file,
       name: 'avatar',
	   	header: {'content-type':'multipart/form-data','token':token} ,
       success: function (res) {
        var data = res.data;
        resolve(JSON.parse(data))
       },
       fail: function (res) {
        reject("上传失败")
       },
       complete: function (res) {
        wx.hideToast();
        wx.hideLoading();
       }
      })
    })
  }
  chooseImage(){
    return new Promise((resolve,reject) => {
      wx.chooseImage({
        count: this.obj.count,
        sizeType: this.obj.sizeType,
        sourceType: this.obj.sourceType,
        success: function (res) {
          resolve(res)
        },
        fail:function(){
          reject("选择文件失败")
        }
      })
    })
  }
}